package com.atguigu.serviceedu.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.serviceedu.client.VodClient;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.commonutils.exception.GuliException;
import com.atguigu.serviceedu.mapper.EduVideoMapper;
import com.atguigu.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author xuan
 * @since 2020-04-13
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    VodClient vodClient;

    @Override
    public boolean edit(EduVideo video) {
        String videoId = video.getId();
        int result = 0;
        if(StringUtils.isEmpty(videoId)){
            result = baseMapper.insert(video);
        }else{
            result = baseMapper.updateById(video);
        }
        if(result==0){
            throw new GuliException(2001,"新增或更新失败");
        }
        return result>0;
    }

    @Override
    public boolean delete(String videoId) {
        EduVideo video = baseMapper.selectById(videoId);
        String videoSourceId = video.getVideoSourceId();
        List<String> list = new ArrayList<>();
        list.add(videoSourceId);
        vodClient.deleteVideoFile(list);
        return baseMapper.deleteById(videoId)>0;
    }

    @Override
    public boolean deleteVideoFile(String videoId) {
        EduVideo video = baseMapper.selectById(videoId);
        String videoSourceId = video.getVideoSourceId();
        List<String> list = new ArrayList<>();
        list.add(videoSourceId);
        R r = vodClient.deleteVideoFile(list);
        video.setVideoOriginalName("").setVideoSourceId("");
        int result = baseMapper.updateById(video);
        return result > 0;
    }
}
